<template>
  <div class="attendance-page">
    <!-- 考勤概览 -->
    <el-row :gutter="20" class="overview-section">
      <el-col :xs="24" :sm="12" :md="6" v-for="card in overviewCards" :key="card.id">
        <el-card class="overview-card" :class="card.type">
          <div class="card-content">
            <div class="card-icon">
              <el-icon :size="28"><component :is="card.icon" /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ card.value }}</div>
              <div class="card-label">{{ card.label }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card>
      <template #header>
        <div class="page-header">
          <h3>考勤管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showSignDialog">
              <el-icon><Clock /></el-icon>
              打卡签到
            </el-button>
            <el-button type="success" @click="showLeaveDialog">
              <el-icon><DocumentAdd /></el-icon>
              请假申请
            </el-button>
            <el-button @click="handleExport">
              <el-icon><Download /></el-icon>
              导出考勤
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="searchForm.department" placeholder="请选择部门" clearable>
            <el-option label="技术部" value="tech" />
            <el-option label="销售部" value="sales" />
            <el-option label="财务部" value="finance" />
          </el-select>
        </el-form-item>
        <el-form-item label="考勤日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="考勤状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="normal" />
            <el-option label="迟到" value="late" />
            <el-option label="早退" value="early" />
            <el-option label="缺勤" value="absent" />
            <el-option label="请假" value="leave" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 考勤记录列表 -->
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="employeeName" label="员工姓名" width="120" />
        <el-table-column prop="department" label="部门" width="120" />
        <el-table-column prop="checkInTime" label="上班打卡" width="120">
          <template #default="{ row }">
            <span :class="{ 'late-time': row.isLate }">{{ row.checkInTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="checkOutTime" label="下班打卡" width="120">
          <template #default="{ row }">
            <span :class="{ 'early-time': row.isEarly }">{{ row.checkOutTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="workHours" label="工作时长" width="100">
          <template #default="{ row }">
            {{ row.workHours }}小时
          </template>
        </el-table-column>
        <el-table-column prop="status" label="考勤状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="打卡地点" width="150" />
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">详情</el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">修正</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 打卡签到对话框 -->
    <el-dialog v-model="signDialogVisible" title="打卡签到" width="500px">
      <div class="sign-content">
        <div class="current-time">
          <el-icon :size="64" color="#409eff"><Clock /></el-icon>
          <div class="time-display">{{ currentTime }}</div>
          <div class="date-display">{{ currentDate }}</div>
        </div>
        
        <el-divider />
        
        <el-form :model="signForm" label-width="100px">
          <el-form-item label="打卡类型">
            <el-radio-group v-model="signForm.type">
              <el-radio label="in">上班打卡</el-radio>
              <el-radio label="out">下班打卡</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="打卡地点">
            <el-input v-model="signForm.location" placeholder="自动获取..." readonly />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="signForm.remark" type="textarea" :rows="3" placeholder="选填" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="signDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSign" :loading="signLoading">确认打卡</el-button>
      </template>
    </el-dialog>

    <!-- 请假申请对话框 -->
    <el-dialog v-model="leaveDialogVisible" title="请假申请" width="600px">
      <el-form :model="leaveForm" :rules="leaveRules" ref="leaveFormRef" label-width="100px">
        <el-form-item label="请假类型" prop="type">
          <el-select v-model="leaveForm.type" placeholder="请选择请假类型" style="width: 100%">
            <el-option label="病假" value="sick" />
            <el-option label="事假" value="personal" />
            <el-option label="年假" value="annual" />
            <el-option label="调休" value="compensatory" />
            <el-option label="婚假" value="marriage" />
            <el-option label="产假" value="maternity" />
          </el-select>
        </el-form-item>
        <el-form-item label="请假时间" prop="dateRange">
          <el-date-picker
            v-model="leaveForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="请假时长">
          <el-input v-model="leaveDuration" readonly>
            <template #append>天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="请假事由" prop="reason">
          <el-input v-model="leaveForm.reason" type="textarea" :rows="4" placeholder="请输入请假事由" />
        </el-form-item>
        <el-form-item label="审批人" prop="approver">
          <el-select v-model="leaveForm.approver" placeholder="请选择审批人" style="width: 100%">
            <el-option label="张三" value="zhangsan" />
            <el-option label="李四" value="lisi" />
          </el-select>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            :file-list="leaveForm.files"
            multiple
          >
            <el-button size="small">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持上传病假条、证明等文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="leaveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitLeave" :loading="leaveLoading">提交申请</el-button>
      </template>
    </el-dialog>

    <!-- 考勤详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="考勤详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="日期">{{ viewData.date }}</el-descriptions-item>
        <el-descriptions-item label="员工姓名">{{ viewData.employeeName }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ viewData.department }}</el-descriptions-item>
        <el-descriptions-item label="上班打卡">{{ viewData.checkInTime }}</el-descriptions-item>
        <el-descriptions-item label="下班打卡">{{ viewData.checkOutTime }}</el-descriptions-item>
        <el-descriptions-item label="工作时长">{{ viewData.workHours }}小时</el-descriptions-item>
        <el-descriptions-item label="考勤状态">
          <el-tag :type="getStatusType(viewData.status)">{{ getStatusText(viewData.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="打卡地点" :span="2">{{ viewData.location }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewData.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const loading = ref(false)
const signDialogVisible = ref(false)
const leaveDialogVisible = ref(false)
const viewDialogVisible = ref(false)
const signLoading = ref(false)
const leaveLoading = ref(false)
const currentTime = ref('')
const currentDate = ref('')
const leaveFormRef = ref(null)

// 概览卡片
const overviewCards = ref([
  { id: 1, label: '今日出勤', value: '156人', icon: 'UserFilled', type: 'primary' },
  { id: 2, label: '今日迟到', value: '3人', icon: 'Warning', type: 'warning' },
  { id: 3, label: '今日请假', value: '8人', icon: 'DocumentCopy', type: 'info' },
  { id: 4, label: '今日缺勤', value: '1人', icon: 'Close', type: 'danger' }
])

// 搜索表单
const searchForm = reactive({
  name: '',
  department: '',
  dateRange: [],
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 100
})

// 打卡表单
const signForm = reactive({
  type: 'in',
  location: '北京市朝阳区望京SOHO',
  remark: ''
})

// 请假表单
const leaveForm = reactive({
  type: '',
  dateRange: [],
  reason: '',
  approver: '',
  files: []
})

// 请假验证规则
const leaveRules = {
  type: [{ required: true, message: '请选择请假类型', trigger: 'change' }],
  dateRange: [{ required: true, message: '请选择请假时间', trigger: 'change' }],
  reason: [{ required: true, message: '请输入请假事由', trigger: 'blur' }],
  approver: [{ required: true, message: '请选择审批人', trigger: 'change' }]
}

// 表格数据
const tableData = ref([
  {
    id: 1,
    date: '2024-01-15',
    employeeName: '张三',
    department: '技术部',
    checkInTime: '09:00:00',
    checkOutTime: '18:00:00',
    workHours: 9,
    status: 'normal',
    isLate: false,
    isEarly: false,
    location: '北京市朝阳区望京SOHO',
    remark: ''
  },
  {
    id: 2,
    date: '2024-01-15',
    employeeName: '李四',
    department: '销售部',
    checkInTime: '09:15:00',
    checkOutTime: '18:00:00',
    workHours: 8.75,
    status: 'late',
    isLate: true,
    isEarly: false,
    location: '北京市朝阳区望京SOHO',
    remark: '地铁延误'
  }
])

const viewData = ref({})

// 计算请假时长
const leaveDuration = computed(() => {
  if (!leaveForm.dateRange || leaveForm.dateRange.length !== 2) return '0'
  
  const start = new Date(leaveForm.dateRange[0])
  const end = new Date(leaveForm.dateRange[1])
  const diffTime = Math.abs(end - start)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  return diffDays.toString()
})

// 方法
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', { hour12: false })
  currentDate.value = now.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    weekday: 'long'
  })
}

const getStatusType = (status) => {
  const map = {
    'normal': 'success',
    'late': 'warning',
    'early': 'warning',
    'absent': 'danger',
    'leave': 'info'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    'normal': '正常',
    'late': '迟到',
    'early': '早退',
    'absent': '缺勤',
    'leave': '请假'
  }
  return map[status] || status
}

const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询成功')
  }, 1000)
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    department: '',
    dateRange: [],
    status: ''
  })
}

const showSignDialog = () => {
  updateTime()
  signDialogVisible.value = true
}

const showLeaveDialog = () => {
  leaveDialogVisible.value = true
}

const confirmSign = () => {
  signLoading.value = true
  
  setTimeout(() => {
    signLoading.value = false
    signDialogVisible.value = false
    ElMessage.success('打卡成功')
  }, 1000)
}

const submitLeave = async () => {
  if (!leaveFormRef.value) return
  
  await leaveFormRef.value.validate((valid) => {
    if (valid) {
      leaveLoading.value = true
      
      setTimeout(() => {
        leaveLoading.value = false
        leaveDialogVisible.value = false
        ElMessage.success('请假申请已提交')
      }, 1000)
    }
  })
}

const handleView = (row) => {
  viewData.value = row
  viewDialogVisible.value = true
}

const handleEdit = (row) => {
  ElMessage.info('修正考勤记录')
}

const handleExport = () => {
  ElMessage.success('导出成功')
}

const handleSizeChange = (size) => {
  pagination.size = size
}

const handleCurrentChange = (page) => {
  pagination.page = page
}

// 定时器
let timeInterval = null

onMounted(() => {
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
})

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.attendance-page {
  padding: 0;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.overview-card.primary { border-left: 4px solid #409eff; }
.overview-card.warning { border-left: 4px solid #e6a23c; }
.overview-card.info { border-left: 4px solid #909399; }
.overview-card.danger { border-left: 4px solid #f56c6c; }

.card-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.overview-card.primary .card-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.overview-card.warning .card-icon { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.overview-card.info .card-icon { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); }
.overview-card.danger .card-icon { background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%); }

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-form {
  margin-bottom: 20px;
}

.late-time {
  color: #e6a23c;
  font-weight: 500;
}

.early-time {
  color: #f56c6c;
  font-weight: 500;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.sign-content {
  padding: 20px 0;
}

.current-time {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 20px 0;
}

.time-display {
  font-size: 36px;
  font-weight: 600;
  color: #303133;
}

.date-display {
  font-size: 16px;
  color: #606266;
}
</style>
